// src/utils/http.js
import { Toast } from '@douyinfe/semi-ui';
import axios from 'axios';

// 创建 axios 实例
const http = axios.create({
  baseURL: 'http://localhost:10086/api',
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，例如添加 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    console.log('response:', response);
    if (response.data.success === false) {
      Toast.error(response.data.msg);
    }
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 处理未授权
          console.error('未授权，请重新登录');
          break;
        case 403:
          // 处理禁止访问
          console.error('拒绝访问');
          break;
        case 404:
          // 处理未找到
          console.error('资源未找到');
          break;
        case 500:
          // 处理服务器错误
          console.error('服务器错误');
          break;
        default:
          console.error('请求错误', error.message);
      }
    } else if (error.request) {
      console.error('请求未响应', error.message);
    } else {
      console.error('请求设置错误', error.message);
    }
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export const get = (url: string, params = {}, config = {}) => {
  return http.get(url, { ...config, params });
};

// 封装 POST 请求
export const post = (url: string, data = {}, config = {}) => {
  return http.post(url, data, config);
};

// 封装 PUT 请求
export const put = (url: string, data = {}, config = {}) => {
  return http.put(url, data, config);
};

// 封装 DELETE 请求
export const del = (url: string, params = {}, config = {}) => {
  return http.delete(url, { ...config, params });
};

// 封装文件上传
export const upload = (url: string, file: any, config = {}) => {
  const formData = new FormData();
  formData.append('file', file);
  return http.post(url, formData, {
    ...config,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export default http;